package cn.action.product;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFeatures;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.struts2.ServletActionContext;

import cn.action.BaseAction;
import cn.beans.Product;
import cn.beans.ProductCategory;
import cn.beans.ProductFile;
import cn.constant.ProductConstant;
import cn.utils.DateFormat;
import cn.utils.DateUtil;
import cn.utils.ImportExcelUtil;
import cn.utils.PageModel;

import com.opensymphony.xwork2.ActionContext;
import com.sun.corba.se.spi.servicecontext.ServiceContext;
/*import com.sun.jmx.remote.util.Service;*/

@SuppressWarnings("unchecked")
public class ProductAction extends BaseAction {

	private Product product;
	private String productId;
	private String pcId;
	private int currentPage;
	private int pageSize;
	private PageModel pm = new PageModel();
	private String errorinfo;
	private String fileId;
	private File[] pic;
	private String[] picFileName;
	private String[] picContentType;
	private List listProductFile;
	private ProductCategory pc;
	private String keywords;
	private String isHot;
	private String isNew;
	private List listProduct;
	private String price;
	private String price1;
	private String categoryid;
	private String offertime;
	private String days;
	private String testing;
	
	private String father;

	
	private String ispromote;
	private File picF;
	private File file;
	private String picFFileName;
	//判断是否主图片
	private String mainPic;
	//判断组图片是否删除
	private String deletePic;
	
	//返回导入产品处理的数据
	private String rows = "";
	
	/**
	 * 添加产品
	 * @return
	 */
	public String addProduct() throws Exception{
		String sadminId = (String)ActionContext.getContext().getSession().get("adminId");
		String sadminName = (String)ActionContext.getContext().getSession().get("adminName");
		if(null == sadminId){
			errorinfo = "Time over";
			return LOGIN;
		}else{
			boolean tag = false;
			
			Double p = Double.valueOf(price);
			
			pc = commonservice.findById(pcId, new ProductCategory());
			product.setCreAdminId(sadminId);
			product.setCreAdminName(sadminName);
			product.setCreDate(new Date());
			product.setLastEditorId(sadminId);
			product.setLastEditorName(sadminName);
			product.setLastEditDate(product.getCreDate());
			product.setCategory(pc);
			product.setPrice(p);
			product.setPv(0);
			product.setCategoryId(pc.getId());
//			if(Double.valueOf(product.getDays())<15){
//				product.setOffertime("0");
//			}else{
//				product.setOffertime("1");
//			}
			
			if(null != picF)
			{
				InputStream is = new FileInputStream(picF);
				int pos = picFFileName.lastIndexOf(".");
				String extName = picFFileName.substring(pos).toLowerCase();
				if(!(".jpg".equals(extName) || ".gif".equals(extName) 
						|| ".jpeg".equals(extName) || ".png".equals(extName))){
						
						errorinfo = "picType";
						return INPUT;
					}else{
				//		String imgUUID = UUID.randomUUID().toString()+extName;
						
						String uploadFilename = DateFormat.getDateId() + extName;
						
						String root = ServletActionContext.getServletContext()
								.getRealPath("/upload/product");
						File app = new File(root);
						if (!app.exists()) {
							app.mkdir();
						}
						
						if(!tag){
							commonservice.saveDemo(product);
							tag = true;
						}
						
						File dest = new File(root, uploadFilename);

						OutputStream os;
						os = new FileOutputStream(dest);
						byte[] buffer = new byte[1024];
						int len = 0;
						int total = 0;
						while ((len = is.read(buffer)) > 0) {
							total += len;
							os.write(buffer, 0, len);
						}
						is.close();
						os.close();
						
						product.setImg(picFFileName);
						product.setImguuid(uploadFilename);
						
						ProductFile pf = new ProductFile();
						pf.setAdminId(sadminId);
						pf.setAdminName(sadminName);
						pf.setCreDate(new Date());
						pf.setExtent(extName);
						pf.setName(picFFileName);
						pf.setSaveName(uploadFilename);
						pf.setSize(total);
						pf.setProduct(product);
						pf.setMainPic("1");
						
						commonservice.saveDemo(pf);
						
					}
			}
			
			if(null != pic){
				int length = pic.length;
				for(int i=0;i<length;i++){
					if(null != pic[i]){
						InputStream is = new FileInputStream(pic[i]);
						int pos = picFileName[i].lastIndexOf(".");
						String extName = picFileName[i].substring(pos).toLowerCase();
						if(!(".jpg".equals(extName) || ".gif".equals(extName) 
							|| ".jpeg".equals(extName) || ".png".equals(extName))){
							
							errorinfo = "picType";
							return INPUT;
						}else{
							if(!tag){
								commonservice.saveDemo(product);
								tag = true;
							}
							
							String uploadFilename = DateFormat.getDateId() + extName;
							String root = ServletActionContext.getServletContext()
									.getRealPath("/upload/product");
							File app = new File(root);
							if (!app.exists()) {
								app.mkdir();
							}
							File dest = new File(root, uploadFilename);

							OutputStream os;
							os = new FileOutputStream(dest);
							byte[] buffer = new byte[1024];
							int len = 0;
							int total = 0;
							while ((len = is.read(buffer)) > 0) {
								total += len;
								os.write(buffer, 0, len);
							}
							is.close();
							os.close();
							
							ProductFile pf = new ProductFile();
							pf.setAdminId(sadminId);
							pf.setAdminName(sadminName);
							pf.setCreDate(new Date());
							pf.setExtent(extName);
							pf.setName(picFileName[i]);
							pf.setSaveName(uploadFilename);
							pf.setSize(total);
							pf.setProduct(product);
							pf.setMainPic("0");
							
							commonservice.saveDemo(pf);
						}
					}
				}
			}else{
		
				commonservice.saveDemo(product);
			}
			return SUCCESS;
		}
	}
	
	/**
	 * 删除产品
	 * @throws Exception
	 */
	public void deleteProduct() throws Exception{
		try{
			
			String[] ids = productId.split(",");
			int length = ids.length;
			for(int i=0;i<length;i++){
				Product p = commonservice.findById(ids[i], new Product());
				if(null != p.getProductFiles()){
					String productPath = ServletActionContext.getServletContext().getRealPath("/upload/product");
					productPath += "\\";
					Iterator iter = p.getProductFiles().iterator();
					while(iter.hasNext()){
						ProductFile pf = (ProductFile)iter.next();
						String file = productPath + pf.getSaveName();
						File f = new File(file);
						if(f.exists()){
							f.delete();
						}
						commonservice.deleteDemo(pf, null);
					}
				}
				commonservice.deleteDemo(p, null);
			}
			
			this.sendMsgAjax("success", null);
			
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 修改产品
	 * @return
	 */
	public String updateProduct() throws Exception{
		
		String sadminId = (String)ActionContext.getContext().getSession().get("adminId");
		String sadminName = (String)ActionContext.getContext().getSession().get("adminName");
		if(null == sadminId){
			errorinfo = "Time Over";
			return LOGIN;
		}else{
			boolean tag = false;
			
			Double pr = Double.valueOf(price);
			
			pc = commonservice.findById(pcId, new ProductCategory());
			Product p = commonservice.findById(productId, new Product());
			p.setTitle(product.getTitle());
			p.setPrice(pr);
			p.setPrice1(product.getPrice1());
			p.setIntroduction(product.getIntroduction());
			p.setCategory(pc);
			p.setCategoryId(pc.getId());
			p.setContent(product.getContent());
			p.setIsHot(product.getIsHot());
			p.setIsNew(product.getIsNew());
			p.setLastEditorId(sadminId);
			p.setLastEditorName(sadminName);
			p.setLastEditDate(new Date());
			p.setProductid(product.getProductid());
			p.setKeyword(product.getKeyword());
			//p.setOffertime(product.getOffertime());
			//根据供货时间判断
//			if(Double.valueOf(product.getDays())<15){
//				p.setOffertime("0");
//			}else{
//				p.setOffertime("1");
//			}
			p.setIspromote(product.getIspromote());
			p.setBrand(product.getBrand());
			p.setProductsize(product.getProductsize());
			p.setSpecification(product.getSpecification());
			p.setStandard(product.getStandard());
			p.setBspecification(product.getBspecification());
			p.setColor(product.getColor());
			p.setWeight(product.getWeight());
			p.setMaterial(product.getMaterial());
			p.setDays(product.getDays());
			
			if(null != picF)
			{
				InputStream is = new FileInputStream(picF);
				int pos = picFFileName.lastIndexOf(".");
				String extName = picFFileName.substring(pos).toLowerCase();
				if(!(".jpg".equals(extName) || ".gif".equals(extName) 
						|| ".jpeg".equals(extName) || ".png".equals(extName))){
						
						errorinfo = "picType";
						return INPUT;
					}else{
				//		String imgUUID = UUID.randomUUID().toString()+extName;
						
						String uploadFilename = DateFormat.getDateId() + extName;
						
						String root = ServletActionContext.getServletContext()
								.getRealPath("/upload/product");
						File app = new File(root);
						if (!app.exists()) {
							app.mkdir();
						}
						
						File dest = new File(root, uploadFilename);

						OutputStream os;
						os = new FileOutputStream(dest);
						byte[] buffer = new byte[1024];
						int len = 0;
						int total = 0;
						while ((len = is.read(buffer)) > 0) {
							total += len;
							os.write(buffer, 0, len);
						}
						is.close();
						os.close();
						
						p.setImg(picFFileName);
						p.setImguuid(uploadFilename);
						
						ProductFile pf = new ProductFile();
						pf.setAdminId(sadminId);
						pf.setAdminName(sadminName);
						pf.setCreDate(new Date());
						pf.setExtent(extName);
						pf.setName(picFFileName);
						pf.setSaveName(uploadFilename);
						pf.setSize(total);
						pf.setProduct(product);
						pf.setMainPic("1");
						pf.setProduct(p);
						
						commonservice.updateDemo(p);
						commonservice.saveDemo(pf);
						
					}
			}
			
			
			if(null != pic){
				int length = pic.length;
				for(int i=0;i<length;i++){
					if(null != pic[i]){
						
						InputStream is = new FileInputStream(pic[i]);
						int pos = picFileName[i].lastIndexOf(".");
						String extName = picFileName[i].substring(pos).toLowerCase();
						if(!(".jpg".equals(extName) || ".gif".equals(extName) 
							|| ".jpeg".equals(extName) || ".png".equals(extName))){
							
							errorinfo = "picType";
							return INPUT;
						}else{
							
							String uploadFilename = DateFormat.getDateId() + extName;
							String root = ServletActionContext.getServletContext()
									.getRealPath("/upload/product");
							File app = new File(root);
							if (!app.exists()) {
								app.mkdir();
							}
							File dest = new File(root, uploadFilename);

							OutputStream os;
							os = new FileOutputStream(dest);
							byte[] buffer = new byte[1024];
							int len = 0;
							int total = 0;
							while ((len = is.read(buffer)) > 0) {
								total += len;
								os.write(buffer, 0, len);
							}
							is.close();
							os.close();
							
							ProductFile pf = new ProductFile();
							pf.setAdminId(sadminId);
							pf.setAdminName(sadminName);
							pf.setCreDate(new Date());
							pf.setExtent(extName);
							pf.setName(picFileName[i]);
							pf.setSaveName(uploadFilename);
							pf.setSize(total);
							pf.setProduct(p);
							pf.setMainPic("0");
							p.setProductid(product.getProductid());
							p.setOffertime(product.getOffertime());
							p.setIspromote(product.getIspromote());
							p.setBrand(product.getBrand());
							p.setProductsize(product.getProductsize());
							p.setSpecification(product.getSpecification());
							p.setStandard(product.getStandard());
							p.setBspecification(product.getBspecification());
							
							commonservice.saveDemo(pf);
						}
					}
				}
				
			}else{
				commonservice.updateDemo(p);
			}
			return SUCCESS;
		}
	}
	
	/**
	 * 产品详情
	 * @return
	 */
	public String productDetail(){
		if(null != productId){
			product = commonservice.findById(productId, new Product());
			if(null != categoryid) {
				father = commonservice.findById(categoryid, new ProductCategory()).getNameCn();
			}
			if(null != product){
				String hql = "FROM ProductFile pf WHERE pf.product.id = ? ORDER BY pf.creDate ASC";
				Object[] param = { product.getId() };
				List list = findSomeByHQL.findDataByHql(hql, param);
				if(null != list && list.size() > 0){
					listProductFile = new ArrayList();
					int size = list.size();
					for(int i=0; i<size; i++){
						ProductFile pf = (ProductFile)list.get(i);
						if(null != pf){
							listProductFile.add(pf);
						}
					}
				}
				ServletActionContext.getRequest().setAttribute("listProductFile", listProductFile);
			}
		}
		return SUCCESS;
	}
	
	public String getProductSize() {
		String hql = "from Product p where p.category.id = ?";
		Object[] params = {categoryid};
		listProduct = findSomeByHQL.findDataByHql(hql, params);
		return SUCCESS;
	}
	
	/**
	 * 获取产品列表
	 * @return
	 */
	public String getProductList(){
		
		try {
			if(null == pcId || "".equals(pcId) || "null".equals(pcId)){
				pcId = "root";
			}
			
			pm.setCurrentPage(currentPage);
			pm.setPageSize(pageSize);
			
			

			List listOne = new ArrayList();
			String[] propertyName = { "category.id", "offertime" };
			String[] propertyCon = { "=","=" };
			Object[] propertyValue = { categoryid, offertime };
			String[] condition = { "and" };
			listOne.add(propertyName);
			listOne.add(propertyCon);
			listOne.add(propertyValue);
			listOne.add(condition);
			
			List listTwo = new ArrayList();
			String[] propertyNameQuery = { "productid", "title", "introduction", "brand", "keyword" };
			String[] propertyConQuery = { "like","like","like","like" ,"like"};
			Object[] propertyValueQuery = { keywords, keywords, keywords, keywords, keywords};
			String[] conditionQuery = { "OR","OR","OR","OR" };
			listTwo.add(propertyNameQuery);
			listTwo.add(propertyConQuery);
			listTwo.add(propertyValueQuery);
			listTwo.add(conditionQuery);

			List listthree = new ArrayList();
			
			String name ="";
			String val = "";
			if( null != isNew && !"null".equals(isNew) && !isNew.isEmpty()){  //&& !isHot.isEmpty()
				name = "isNew";
				val =  isNew;
			}else if(null != isHot && !"null".equals(isHot) && !isHot.isEmpty() ){
				name = "isHot";
				val = isHot;
			}else if(null != ispromote && !"null".equals(ispromote) && !ispromote.isEmpty() ){
				name = "ispromote";
				val = ispromote;
			}
			
			String[] propertyName3 = { name };
			String[] propertyCon3 = { "=" };
			Object[] propertyValue3 = {val };
			String[] condition3 = null;
			listthree.add(propertyName3);
			listthree.add(propertyCon3);
			listthree.add(propertyValue3);
			listthree.add(condition3);

			String[] orderPropertyName = { "isHot","isNew","lastEditDate" };
			String[] orderValue = { "DESC", "DESC", "DESC" };
			
			if( !"".equals(name) && !"".equals(val) ){
					pm = commonservice.findDataByPage(pm, "Product", listOne, "AND", listTwo, "AND", listthree, null, null, orderPropertyName, orderValue);
				}else{
					pm = commonservice.findDataByPage(pm, "Product", listOne, "AND", listTwo,null,null, null, null, orderPropertyName, orderValue);
				}
			

			List list = pm.getList();
			//在每个产品添加产品类型
			for(int n = 0;n<list.size();n++)
			{
				String fName = "";
				Product product= (Product)list.get(n);
				String categoryId = ((ProductCategory)product.getCategory()).getParentId();
				if("root".equals(categoryId)){
					fName = ((ProductCategory)product.getCategory()).getNameCn();
				}else{
					fName = ((ProductCategory)product.getCategory()).getNameCn();
					categoryId = ((ProductCategory)product.getCategory()).getParentId();
					for(int m = 0 ;m <list.size();m++){
						Product product1= (Product)list.get(m);
						String categoryId2 = ((ProductCategory)product1.getCategory()).getId();
						if(categoryId.equals(categoryId2)){
							fName = ((ProductCategory)product1.getCategory()).getNameCn()+"/"+fName;
							break;
						}
					}
				}
				product.setFathername(fName);
			}
			
			
			int size = list.size();
			picFileName = new String[size];
			for(int i=0; i<size; i++){
				Product p = (Product)list.get(i);
				String hql = "FROM ProductFile pf WHERE pf.product.id = ? ORDER BY pf.creDate ASC";
				Object[] param = { p.getId() };
				List listPf = findSomeByHQL.findDataByHql(hql, param);
				if(null != listPf && listPf.size() > 0){
					ProductFile pf = (ProductFile)listPf.get(0);
					picFileName[i] = pf.getSaveName();
				}
			}
			return SUCCESS;
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return SUCCESS;
		}
	}
	
	/**
	 * 用于显示首页的产品列表,包括Hot和New
	 * @return
	 */
	public String indexList(){
		
		if(null != isHot){
			
			String hql = "FROM Product p WHERE p.isHot = ? ORDER BY p.lastEditDate DESC";
			Object[] param = new Object[]{ ProductConstant.IS_HOT };
			
			List list = findSomeByHQL.findDataByHql(hql, param);
			if(null != list && list.size() > 0){
				listProduct = new ArrayList();
				int size = list.size();
				if("6".equals(isHot)){
					size = list.size() > ProductConstant.INDEX_HOT?ProductConstant.INDEX_HOT:list.size();
				}else if("10".equals(isHot)){
					size = list.size() > ProductConstant.PRODUCT_HOT?ProductConstant.PRODUCT_HOT:list.size();
				}
				for(int i=0;i<size;i++){
					Product p = (Product)list.get(i);
					String hqlPic = "FROM ProductFile pf WHERE pf.product.id = ? ORDER BY pf.creDate ASC";
					Object[] paramPic = { p.getId() };
					List listPic = findSomeByHQL.findDataByHql(hqlPic, paramPic);
					Object[] obj;
					if(null != listPic && listPic.size() > 0){
						obj = new Object[]{ p, listPic.get(0) };
					}else{
						obj = new Object[]{ p, new ProductFile() };
					}
					listProduct.add(obj);
				}
			}
			
		}else if(null != isNew){
			String hql = "FROM Product p WHERE p.isNew = ? ORDER BY p.lastEditDate DESC";
			Object[] param = new Object[]{ ProductConstant.IS_NEW };
			
			List list = findSomeByHQL.findDataByHql(hql, param);
			if(null != list && list.size() > 0){
				listProduct = new ArrayList();
				int size = list.size() > ProductConstant.INDEX_NEW?ProductConstant.INDEX_NEW:list.size();
				for(int i=0;i<size;i++){
					Product p = (Product)list.get(i);
					String hqlPic = "FROM ProductFile pf WHERE pf.product.id = ? ORDER BY pf.creDate ASC";
					Object[] paramPic = { p.getId() };
					List listPic = findSomeByHQL.findDataByHql(hqlPic, paramPic);
					Object[] obj;
					if(null != listPic && listPic.size() > 0){
						obj = new Object[]{ p, listPic.get(0) };
					}else{
						obj = new Object[]{ p, new ProductFile() };
					}
					listProduct.add(obj);
				}
			}
		}
		
		return SUCCESS;
		
	}
	
	/**
	 * 修改产品时,删除产品展示图片
	 * @throws Exception
	 */
	public void deleteProductFile() throws Exception{
		try{
			String sadminId = (String)ActionContext.getContext().getSession().get("adminId");
			if(null == sadminId){
				this.sendMsgAjax("login", null);
			}else{
				ProductFile pf = commonservice.findById(fileId, new ProductFile());
				
				String mainPic ="";;
				//删除主图片
				if(pf != null ){
					mainPic = pf.getMainPic();
					
					//判断是否主图片  1是主图片 0不是
					if(!mainPic.isEmpty() && mainPic != null && !("null").equals(mainPic) && "1".equals(mainPic)){
						
						Product pro = pf.getProduct();
						pro.setImg("");
						pro.setImguuid("");
						
					}else{
						String productPath = ServletActionContext.getServletContext().getRealPath("/upload/product");
						String file = productPath + "\\" + pf.getSaveName();
						File f = new File(file);
						if(f.exists()){
							f.delete();
						}
					}
					
				}
				
				if(pf != null && "1".equals(mainPic)){
					commonservice.deleteDemo(pf, null);
					
					String productPath = ServletActionContext.getServletContext().getRealPath("/upload/product");
					String file = productPath + "\\" + pf.getSaveName();
					File f = new File(file);
					if(f.exists()){
						f.delete();
					}
					
					this.sendMsgAjax("successf", null);
				}else if(pf != null && "0".equals(mainPic)){
					commonservice.deleteDemo(pf, null);
					this.sendMsgAjax("success", null);
				}else{
					this.sendMsgAjax("error", null);
				}
				
			}
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 导入产品excel
	 * 参数：
	 * @return
	 */
	public String saveExcel()throws Exception {
		
		String configType = "ProductLegal.xml";
		
	//	File file = new File("C://new_product.xls");
		
		ImportExcelUtil importExcelUtil=new ImportExcelUtil();
		
		Map session=ServletActionContext.getContext().getSession();
		
		List<Product> listC=importExcelUtil.getExcelObjectList(configType,file,session);
		
		String productPath = ServletActionContext.getServletContext().getRealPath("/upload/product");
		
		String picerror = "";
		String picerrorlog = "";
		File filetest = null;
		System.out.println(listC.size()+"=====================");
		if(null != listC && !listC.isEmpty()){
			for(int i =0 ;i<listC.size();i++){
				//参数处理
				String introduction ="";
				String content = "";
				//给内容加div标签
				if(null==listC.get(i).getIntroduction()||"".equals(listC.get(i).getIntroduction())){
					introduction = "";
				}else{
					introduction = listC.get(i).getIntroduction();
				}
				content = "<div>"+introduction+"</div>";
				listC.get(i).setContent(content);
				
				if(null==listC.get(i).getIsHot()||"".equals(listC.get(i).getIsHot())){
					listC.get(i).setIsHot("0");
				}
				if(null==listC.get(i).getIsNew()||"".equals(listC.get(i).getIsNew())){
					listC.get(i).setIsNew("0");
				}	
				if(null==listC.get(i).getIspromote()||"".equals(listC.get(i).getIspromote())){
					listC.get(i).setIspromote("0");
				}						
				if(null==listC.get(i).getPrice()||"".equals(listC.get(i).getPrice())){
					listC.get(i).setPrice(0.0);
				}
				if(null==listC.get(i).getPrice1()||"".equals(listC.get(i).getPrice1())){
					listC.get(i).setPrice1("暂无提供");
				}
				if(null==listC.get(i).getOffertime()||"".equals(listC.get(i).getOffertime())){
					listC.get(i).setOffertime("0");
				}
				
				pc = commonservice.findById(listC.get(i).getCategoryId(), new ProductCategory());
				listC.get(i).setCategory(pc);
				//listC.get(i).setImg(listC.get(i).getProductid()+".jpg");
				//listC.get(i).setImguuid(listC.get(i).getProductid()+".jpg");
				//2011年10月15日将图片路径的规则从编号+.jpg改为型号规格+.jpg
				//判断用户是否没有重命名_序号的名字格式，自动寻找校正
				filetest =new File( productPath+"\\"+listC.get(i).getBspecification()+".jpg");
				System.out.println(listC.get(i).getBspecification()+".jpg"+"222222222222222");
				if(null != filetest && filetest.length() != 0){
					listC.get(i).setImg(listC.get(i).getBspecification()+".jpg");
					listC.get(i).setImguuid(listC.get(i).getBspecification()+".jpg");
				}else{
					listC.get(i).setImg(listC.get(i).getBspecification()+"_1.jpg");
					listC.get(i).setImguuid(listC.get(i).getBspecification()+"_1.jpg");					
				}
				
//				if(null!=listC.get(i).getDays()&&!"".equals(listC.get(i).getDays())){
//					if(Double.valueOf(listC.get(i).getDays())<15){
//						listC.get(i).setOffertime("0");
//					}else{
//						listC.get(i).setOffertime("1");
//					}
//				}else{
//					listC.get(i).setOffertime("1");
//					listC.get(i).setDays("15");
//				}
				if(null==listC.get(i).getTitle()||"".equals(listC.get(i).getTitle())){
					listC.get(i).setTitle(listC.get(i).getBspecification());
				}
			}
			if(testing.equals("0")){
				super.commonservice.saveOrUpdateAll(listC);
			}
			
			ProductFile p = null;
			List<ProductFile> listProductFile = new ArrayList();
			int j = 0;
			String imgName = "";
			String extent = "";
			int pictures =0;
			for(int i =0;i<listC.size();i++){
			//	String productId = listC.get(i).getId();
				if(null==listC.get(i).getPictures()||"".equals(listC.get(i).getPictures())){
					pictures = 1 ;
				}else{
					pictures = listC.get(i).getPictures();
				}
				for(j = 1; j<pictures+1;j++){
				if(j>5){
					break;//超出5张图无效
				}
				if(j>1){
					if(imgName.lastIndexOf("_1.jpg")>0){
						imgName = listC.get(i).getImg().substring(0, listC.get(i).getImg().lastIndexOf(".jpg")-1)+j+".jpg";
					}else{
						imgName = listC.get(i).getImg().substring(0, listC.get(i).getImg().lastIndexOf(".jpg"))+"_"+j+".jpg";
					}
				}else{
					imgName = listC.get(i).getImg();
				}
				extent= ".jpg";
				int size = 0;
				File file =new File( productPath+"\\"+imgName);
				if(null != file && file.length() != 0){
					//System.out.println("size:"+file.length());
					size = Integer.parseInt(String.valueOf(file.length()));
					if(imgName.indexOf("—")>0){
					picerror = "<p>"+picerror+listC.get(i).getProductid()+"的图片"+imgName+"含有中文连字符—，请修改该产品的规格型号，改成英文连字符，并将图片重命名;</p>";
					//imgName=imgName.replaceAll("—", "-");
					}
				}else{
					picerror = "<p>"+picerror+listC.get(i).getProductid()+"的图片"+imgName+"未找到;</p>";
					picerrorlog = picerrorlog+listC.get(i).getProductid()+"的图片"+imgName+"未找到;";
				}
				String admin_id = listC.get(i).getLastEditorId();
				String admin_name = listC.get(i).getLastEditorName();
				p = new ProductFile();
				p.setName(imgName);
				p.setSaveName(imgName);
				p.setExtent(extent);
				p.setSize(size);
				p.setAdminId(admin_id);
				p.setAdminName(admin_name);
				p.setCreDate(new Date());
				p.setProduct(listC.get(i));
				if(j==1){
					p.setMainPic("1");
				}else{
					p.setMainPic("0");
				}
				listProductFile.add(p);
				}
			}
			
			if(!listProductFile.isEmpty() && null != listProductFile){
				if(testing.equals("0")){
				super.commonservice.saveOrUpdateAll(listProductFile);
				}
			}
		}
		if(testing.equals("0")){//导入数据
		if(picerror.length()>1){
			rows = "<div style='color:#ff0000;'>已成功导入"+listC.size()+"行产品数据。</div><div style='color:#ff0000;'><br/><p>警告：</p>"+picerror+"</div>";
		}else{
			rows = "<div style='color:#ff0000;'>已成功导入"+listC.size()+"行产品数据。</div>";
		}
		//保存导入数据历史
		String importlogPath = ServletActionContext.getServletContext().getRealPath("/upload/product");
		   FileWriter fw = new FileWriter(importlogPath+"/产品导入日志_"+DateFormat.getDateId()+".txt");
		   String[] lines = picerrorlog.split(";");
		   BufferedWriter bw = new BufferedWriter(fw);
		   bw.write("产品导入日志\r\n\r\n");
		   bw.write("操作员："+(String)ActionContext.getContext().getSession().get("adminId")+"\r\n");
		   SimpleDateFormat timetemp=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	       String timeStr=timetemp.format(new Date());
		   bw.write("时　间："+timeStr+"\r\n\r\n");
		   
		   bw.write("结　果：\r\n");
		   bw.write("　　成功导入"+listC.size()+"行产品数据。\r\n");
		   
		   if(lines.length>0){
		   bw.write("\r\n警　告：\r\n");
		   for (int i = 0; i < lines.length; i++) {
		    bw.write((i+1)+"、"+lines[i] + "\r\n");
		   }
		   }else{
			   bw.write("\r\n无异常数据\r\n");
		   }
		   bw.close();
		}else{//测试数据
			if(picerror.length()>1){
				rows = "<div style='color:#ff0000;'>成功找到"+listC.size()+"行产品数据。</div><div style='color:#ff0000;'><br/><p>警告：</p>"+picerror+"</div>";
			}else{
				rows = "<div style='color:#ff0000;'>成功找到"+listC.size()+"行产品数据。</div><div style='color:#ff0000;'><br/><p>恭喜您，您的数据符合导入规则，并且能匹配上所有图片。</p>"+picerror+"</div>";
			}
			//保存导入数据历史
			String importlogPath = ServletActionContext.getServletContext().getRealPath("/upload/product");
			   FileWriter fw = new FileWriter(importlogPath+"/产品导入日志_"+DateFormat.getDateId()+".txt");
			   String[] lines = picerrorlog.split(";");
			   BufferedWriter bw = new BufferedWriter(fw);
			   bw.write("产品测试导入日志\r\n\r\n");
			   bw.write("操作员："+(String)ActionContext.getContext().getSession().get("adminId")+"\r\n");
			   SimpleDateFormat timetemp=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		       String timeStr=timetemp.format(new Date());
			   bw.write("时　间："+timeStr+"\r\n\r\n");
			   
			   bw.write("结　果：\r\n");
			   bw.write("　　成功找到"+listC.size()+"行产品数据。\r\n");
			   
			   if(lines.length>0){
			   bw.write("\r\n警　告：\r\n");
			   for (int i = 0; i < lines.length; i++) {
			    bw.write((i+1)+"、"+lines[i] + "\r\n");
			   }
			   }else{
				   bw.write("\r\n无异常数据\r\n");
			   }
			   bw.close();
		}

		return SUCCESS;
	}
	
	/**
	 * 导出产品excel文档模板
	 * @return
	 */
	public InputStream getExcep(){
		
		ActionContext act= ServletActionContext.getContext();
		InputStream in=null;
		try{
			
			ByteArrayOutputStream ost=new ByteArrayOutputStream();
			WritableWorkbook  wwb = Workbook.createWorkbook(ost);
			
			WritableSheet sheet=wwb.createSheet("sheet0", 0);
		
			String parentId = "root";
			
			List list = getpRroductCategrop(parentId);
			
			List angerlist = new ArrayList();
			String nameCN ="";
			String id = "";
			String str = "";
			String parentid = "";
			Label lab ;
			
			if(null != list && 0 != list.size()){
				int m = 0 ;
				int size = list.size();
				for(int i=0; i<size; i++){
					ProductCategory category = (ProductCategory)list.get(i);
					nameCN = category.getNameCn();
					id = String.valueOf(category.getId());
					parentid = category.getParentId();
					if(!parentid.isEmpty() && null != parentid && !"null".equals(parentid) && "root".equals(parentid)){
						str = nameCN+"_"+id;
						lab = new Label(21,2+i+m,str);
						sheet.addCell(lab);
						
						List list2 = getpRroductCategrop(category.getId());
						for(int j = 0 ;j<list2.size();j++){
							m++;
							ProductCategory category2 = (ProductCategory)list2.get(j);
							nameCN = category2.getNameCn();
							id = String.valueOf(category2.getId());
							str = " |-"+nameCN+"_"+id;
							lab = new Label(21,2+i+m,str);
							sheet.addCell(lab);
						}
					}
				}
			}
			
			/*
			Label lab ;
			//System.out.println("angerlist.size():"+angerlist.size());
			for(int i = 0; i<300;i++){
				lab = new Label(17,2+i,"请选择");
				WritableCellFeatures ws = new WritableCellFeatures();  
				ws.setDataValidationList(angerlist);  
				lab.setCellFeatures(ws);  
				sheet.addCell(lab);
			}*/
			
			
			Label l1 = new Label(0,0,"产品表   ");
			sheet.mergeCells(0, 0, 10, 0);
			Label l2 = new Label(0,1,"产品编号");
			Label l3 = new Label(1,1,"产品名称");
			Label l4 = new Label(2,1,"产品简介");
			Label l5 = new Label(3,1,"产品价格");
			Label l6 = new Label(4,1,"是否热销（0=不热销，1=热销）");
			Label l7 = new Label(5,1,"是否新品上架(0=不是新品,1=新品)");
			Label l8 = new Label(6,1,"是否推销(0=不推销，1=推销)");
			Label l10 = new Label(7,1,"品牌");
			Label l11 = new Label(8,1,"产品尺寸");
			Label l12 = new Label(9,1,"包装规格");
			Label l13 = new Label(10,1,"执行标准");
			Label l14 = new Label(11,1,"型号规格");
			Label l15 = new Label(12,1,"颜色");
			Label l16 = new Label(13,1,"重量");
			Label l17 = new Label(14,1,"材质");
			Label l18 = new Label(15,1,"供货价");
			Label l19 = new Label(16,1,"供货时间");
			Label l20 = new Label(17,1,"库存状态(0=15天之内 ，1= 15天之后)");
			Label l21 = new Label(18,1,"初始图片数");
			Label l22 = new Label(19,1,"主题关键词");
			Label l23 = new Label(20,1,"产品分类");
			
			sheet.addCell(l1);
			sheet.addCell(l2);
			sheet.addCell(l3);
			sheet.addCell(l4);
			sheet.addCell(l5);
			sheet.addCell(l6);
			sheet.addCell(l7);
			sheet.addCell(l8);
			//sheet.addCell(l9);
			sheet.addCell(l10);
			sheet.addCell(l11);
			sheet.addCell(l12);
			sheet.addCell(l13);
			sheet.addCell(l14);
			sheet.addCell(l15);
			sheet.addCell(l16);
			sheet.addCell(l17);
			sheet.addCell(l18);
			sheet.addCell(l19);
			sheet.addCell(l20);
			sheet.addCell(l21);
			sheet.addCell(l22);
			sheet.addCell(l23);
			
			wwb.write();
			wwb.close();
			in=new ByteArrayInputStream(ost.toByteArray());;
			ost.close();
	
		}catch(IOException e) {
			act.put("errorinfo", "I/O流出错！");
			in=null;
			e.printStackTrace();
		} catch (RowsExceededException e) {
			act.put("errorinfo", "excel表返回行数出错！");
			in=null;
			e.printStackTrace();
		} catch (WriteException e) {
			act.put("errorinfo", "excel写入出错！");
			in=null;
			e.printStackTrace();
		}catch (Exception e) {
			act.put("errorinfo", "excel写入出错！");
			in=null;
			e.printStackTrace();
		}
		return in;
	}
	
	/***
	 * 返回类目
	 */
	public List getpRroductCategrop(String parentId){
		if(null == parentId && "".equals(parentId)){
			parentId = "root";
		}
		String hql = "FROM ProductCategory AS pc WHERE pc.parentId = ? ORDER BY pc.turnnumber";
		Object[] param = { parentId };
		List list = findSomeByHQL.findDataByHql(hql, param);
		return list;
	}
	
	/**
	 * 导入excel入口函数
	 * @return
	 */
	public String export(){
		
		return SUCCESS;
	}
	
	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public PageModel getPm() {
		return pm;
	}

	public void setPm(PageModel pm) {
		this.pm = pm;
	}
	
	public String getErrorinfo() {
		return errorinfo;
	}

	public void setErrorinfo(String errorinfo) {
		this.errorinfo = errorinfo;
	}

	public String getPcId() {
		return pcId;
	}

	public void setPcId(String pcId) {
		this.pcId = pcId;
	}

	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}

	public File[] getPic() {
		return pic;
	}

	public void setPic(File[] pic) {
		this.pic = pic;
	}

	public String[] getPicFileName() {
		return picFileName;
	}

	public void setPicFileName(String[] picFileName) {
		this.picFileName = picFileName;
	}

	public String[] getPicContentType() {
		return picContentType;
	}

	public void setPicContentType(String[] picContentType) {
		this.picContentType = picContentType;
	}

	public List getListProductFile() {
		return listProductFile;
	}

	public void setListProductFile(List listProductFile) {
		this.listProductFile = listProductFile;
	}

	public ProductCategory getPc() {
		return pc;
	}

	public void setPc(ProductCategory pc) {
		this.pc = pc;
	}

	public String getKeywords() {
		return keywords;
	}

	public void setKeywords(String keywords) {
		this.keywords = keywords;
	}

	public String getIsHot() {
		return isHot;
	}

	public void setIsHot(String isHot) {
		this.isHot = isHot;
	}

	public String getIsNew() {
		return isNew;
	}

	public void setIsNew(String isNew) {
		this.isNew = isNew;
	}

	public List getListProduct() {
		return listProduct;
	}

	public void setListProduct(List listProduct) {
		this.listProduct = listProduct;
	}

	public String getPrice() {
		return price;
	}

	public void setPrice(String price) {
		this.price = price;
	}

	public String getIspromote() {
		return ispromote;
	}

	public void setIspromote(String ispromote) {
		this.ispromote = ispromote;
	}

	public String getCategoryid() {
		return categoryid;
	}

	public void setCategoryid(String categoryid) {
		this.categoryid = categoryid;
	}

	public String getOffertime() {
		return offertime;
	}

	public void setOffertime(String offertime) {
		this.offertime = offertime;
	}

	public File getPicF() {
		return picF;
	}

	public void setPicF(File picF) {
		this.picF = picF;
	}

	public String getPicFFileName() {
		return picFFileName;
	}

	public void setPicFFileName(String picFFileName) {
		this.picFFileName = picFFileName;
	}

	public String getMainPic() {
		return mainPic;
	}

	public void setMainPic(String mainPic) {
		this.mainPic = mainPic;
	}

	public String getDeletePic() {
		return deletePic;
	}

	public void setDeletePic(String deletePic) {
		this.deletePic = deletePic;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

	public String getPrice1() {
		return price1;
	}

	public void setPrice1(String price1) {
		this.price1 = price1;
	}

	public String getDays() {
		return days;
	}

	public void setDays(String days) {
		this.days = days;
	}

	public String getTesting() {
		return testing;
	}

	public void setTesting(String testing) {
		this.testing = testing;
	}

	public String getFather() {
		return father;
	}

	public void setFather(String fathername) {
		this.father = fathername;
	}

	


}
